package com.bjypc.youth.service.impl;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.hibernate.Hibernate;
import org.springframework.transaction.annotation.Transactional;

import com.bjypc.youth.common.PageResult;
import com.bjypc.youth.common.QueryCriteria;
import com.bjypc.youth.dao.IResearchArticleDao;
import com.bjypc.youth.entity.ResearchArticle;
import com.bjypc.youth.service.BaseAbstractService;
import com.bjypc.youth.service.IResearchArticleService;
import com.bjypc.youth.util.ComputeHash;
import com.bjypc.youth.util.SystemUtils;

@Transactional
public class ResearchArticleServiceImpl extends BaseAbstractService implements
		IResearchArticleService {
	private String downloadPath;
	private IResearchArticleDao researchArticleDao;
	private Logger logger = Logger.getLogger(getClass());

	public ResearchArticleServiceImpl() {
		super();
	}

	public ResearchArticle find(Long id) {
		return this.researchArticleDao.findById(id);
	}

	public List<ResearchArticle> findAll() {
		return this.researchArticleDao.findAll();
	}

	public void remove(Long id) {
		this.researchArticleDao.removeById(id);
	}

	public void save(ResearchArticle article) {
		this.researchArticleDao.save(article);

	}

	public IResearchArticleDao getResearchArticleDao() {
		return researchArticleDao;
	}

	public void setResearchArticleDao(IResearchArticleDao researchArticleDao) {
		this.researchArticleDao = researchArticleDao;
	}

	public void iterateArticles(String fromFolder) {

		logger.info("All articles in db are removed");
		this.researchArticleDao.removeAll();

		String folder = fromFolder;
		// scan
		File file = new File(folder);
		File[] filesList = file.listFiles();
		int i = 0;
		for (File subFolder : filesList) {
			if (subFolder.isDirectory()) {
				String folderName = subFolder.getName();

				i++;
				// parse each articles into array
				parseArticle(subFolder, i, folderName);
			}
		}
	}

	private void parseArticle(File subFolder, int articleNum, String folderName) {
		File[] articles = subFolder.listFiles();
		for (File article : articles) {

			String name = article.getName();
			String path = article.getAbsolutePath();
			int index = name.indexOf(".doc");
			String md5 = ComputeHash.getHash(article);
			String title = null;
			// 判断不能是word临时文件，不能是空白文件
			if (!name.startsWith("~$")
					&& !name.startsWith("新建 Microsoft Word 文档") && index != -1) {
				title = name.substring(0, index);
				Date date = SystemUtils.parseDate(article.lastModified());

				if (title != null && title.length() > 0) {

					byte[] wordcontents = new byte[1];
					try {
						wordcontents = FileUtils.readFileToByteArray(article);
					} catch (IOException e) {
						e.printStackTrace();
					}

					ResearchArticle researchArticle = new ResearchArticle();
					setSubContent(path, name, researchArticle);
					researchArticle.setTitle(title);
					researchArticle.setFilePath(path);
					researchArticle.setSuffix(".doc");
					researchArticle.setType(folderName);

					researchArticle.setPublishDate(date);
					researchArticle.setContent(Hibernate
							.createBlob(wordcontents));
					researchArticle.setMd5(md5);

					logger.info("Article with title[" + title
							+ "] not found in db,persist it");
					this.researchArticleDao.save(researchArticle);
					saveArticleToDisk(researchArticle, this.downloadPath);

				}
			}

		}
	}

	private void saveArticleToDisk(ResearchArticle researchArticle,
			String destDir) {
		File saveFilePath = new File(destDir);
		logger.info(saveFilePath.getAbsolutePath());
		if (saveFilePath.exists() && saveFilePath.isDirectory()) {
			String fileName = this.downloadPath + File.separator
					+ researchArticle.getId() + researchArticle.getSuffix();
			try {
				InputStream inputStream = researchArticle.getContent()
						.getBinaryStream();
				int available = inputStream.available();
				if (available > 0) {
					byte[] content = new byte[available];
					inputStream.read(content);
					System.out.println("writing file " + fileName
							+ " to disk with size " + content.length);
					FileUtils.writeByteArrayToFile(new File(fileName), content);
				}
			} catch (SQLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}

	}

	private void setSubContent(String path, String name,
			ResearchArticle researchArticle) {
		String brief = "";
		String author = "";
		String txtFileName = path.replace(".doc", ".txt");
		File txtFile = new File(txtFileName);
		try {
			List<String> lines = FileUtils.readLines(txtFile);
			if (lines.size() > 0) {
				if (lines.size() > 2) {
					String line2 = lines.get(2);
					System.out.println(line2);
					if (line2.length() > 20) {// sub title
						line2 = lines.get(3);
						if (line2.length() > 20) {
							author = "暂无";
						} else {
							author = line2;
						}
					} else {
						author = line2;
					}
				}

				for (String line : lines) {
					if (line.length() > 30) {
						System.out.println("brief:" + line);
						brief = line;
						break;
					}
				}
			}
			researchArticle.setAuthor(author);
			researchArticle.setSubContent(brief);
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	public static void main(String[] args) {
		// ResearchArticleServiceImpl researchArticleServiceImpl = new
		// ResearchArticleServiceImpl();
		// researchArticleServiceImpl.iterateArticles();
	}

	public String getDownloadPath() {
		return downloadPath;
	}

	public void setDownloadPath(String downloadPath) {
		this.downloadPath = downloadPath;
	}

	public void setWritePath(String path) {
		this.downloadPath = path;

	}

	public PageResult pageQuery(int start, int limit) {
		QueryCriteria queryCriteria = new QueryCriteria();
		queryCriteria.setCurrentIndex(start);
		queryCriteria.setPageSize(limit);
		String ql = "select id,title,author,type,subContent,suffix,publishDate  from ResearchArticle r";
		return this.researchArticleDao.query(ql, queryCriteria);
	}

}
